import {getComponentRootDom} from "@/utils";
import Icon from "@/components/Icon";
import styles from "./message.module.less"
/**
 * 弹出消息框
 * @param {String} info 消息内容
 * @param {String} type 消息类型 它接受以下几个值：info | error | warn | success
 * @param {HTMLElement} container 容器，消息框会在这个容器里面居中，默认body
 * @param {Number} duration 消息框停留时间，默认值：1500毫秒
 * @param {Function} callback 回调函数，弹出框消失的时候执行
 */
export default function (
    info,
    type = "info",
    container,
    duration = 1500,
    callback
) {
    const div = document.createElement("div");
    const iconElement = getComponentRootDom(Icon, {type});
    div.innerHTML = `<span class="${styles.icon}">${iconElement.outerHTML}</span><div>${info}</div>`
    if(! container) {
        container = document.body;
    } else {
        if(getComputedStyle(container).position === "static" && container !== document.body) {
            container.style.position = "relative"
        }
    }
    const divBg = styles[`message-${type}`];
    div.classList.add(divBg);
    div.classList.add(styles.message);
    container.appendChild(div);
    div.clientHeight; // 让浏览器强行渲染一次
    div.style.opacity = "1";
    div.style.transform = `translate(-50%, -50%)`;

    setTimeout(() => {
        div.style.opacity = "0";
        div.style.transform = `translate(-50%, -50%) translateY(25px)`;
        div.addEventListener("transitionend", function () {
            this.remove();
            callback && callback();
        })
    }, duration)
}
